<?php
/**
 * Created by Benjamin.
 * Date: 2020/5/9
 * Time: 9:38
 */

namespace App\Process;

use App\HttpController\UserGroup;
use App\Model\UserGroupModel;
use App\Services\HelpService;
use App\Services\PrivateMsgService;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Component\TableManager;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Config;

class Subscribe  extends AbstractProcess
{
    public function run($arg)
    {
        // TODO: Implement run() method.
      go(function () use ($arg) {
           $redis = new \EasySwoole\Redis\Redis(new \EasySwoole\Redis\Config\RedisConfig([
                    'host'      => Config::getInstance()->getConf('REDIS.host'),
                    'port'      => Config::getInstance()->getConf('REDIS.port'),
                    'auth' => Config::getInstance()->getConf('REDIS.auth')
                ]));

          $redis->subscribe(function (\EasySwoole\Redis\Redis $redis, $pattern, $str) {
              $messageArr = json_decode($str, true);
              echo '收到群消息' . PHP_EOL;

              $table = TableManager::getInstance()->get(Config::getInstance()->getConf('CHAT.online_user'));
              //获取群成员信息
              try {
                  #当是用户被移除、群解散，即便离开群大家也是都能收到
                  $dataArr = json_decode($messageArr['data'],true);
                  $specialArr = [
                      PrivateMsgService::MSG_TYPE_GROUP_DEL,
                      PrivateMsgService::MSG_TYPE_GROUP_REMOVE
                  ];
                  if( in_array( $dataArr['type'],$specialArr)){
                      $groupList = UserGroupModel::create()->field(['app_user_id,user_id'])->all(['group_id' =>$messageArr['group_id']]);
                      echo '获取成员成功'.PHP_EOL;
                  }else{
                      $groupList = UserGroupModel::create()->field(['app_user_id,user_id'])->all(['group_id' =>$messageArr['group_id'],'status'=>UserGroupModel::STATUS_NORMAL]);
                      echo '获取成员成功'.PHP_EOL;
                  }

              } catch (\Throwable $t) {
                  echo '获取成员失败'.PHP_EOL;
                  return false;
              }
              echo '遍历群成员'.PHP_EOL;
              foreach ($groupList as $member) {
                  echo '成员信息'.PHP_EOL;
                  $onlineInfoArr = $table->get($member['user_id']);
                  if (empty($onlineInfoArr)) {
                      echo $member . '不在线' . PHP_EOL;
                      continue;
                  }
                  echo '在线用户' . PHP_EOL;
                  if ($onlineInfoArr['server'] != Config::getInstance()->getConf('APP.CURRENT')['host']) {
                      continue;
                  }
                  #校验用户是否就绪
                  $readyTable =  TableManager::getInstance()->get(Config::getInstance()->getConf('CHAT.user_ready'));
                  $readyInfo = $readyTable->get($member['user_id']);
                  if(empty($readyInfo)){
                      continue;
                  }
                  $server = ServerManager::getInstance()->getSwooleServer();
                  $info = $server->getClientInfo($onlineInfoArr['fd']);
                  $fdToAppTable = TableManager::getInstance()->get(Config::getInstance()->getConf('CHAT.fd_to_app'));
                  $fdToApp = $fdToAppTable->get($onlineInfoArr['fd']);

                  echo '要开始发消息了' . PHP_EOL;
                  if ($info && $info['websocket_status'] == WEBSOCKET_STATUS_FRAME && !empty($fdToApp)) {
                      //本机推送
                      $server->push($onlineInfoArr['fd'], HelpService::aesEncrypt(json_encode($messageArr), $fdToApp['access_key'], $fdToApp['secret_key']));
                      echo '推送本机群聊' . PHP_EOL;
                      //更新用户最新阅读消息id
                  }
              }


          },Config::getInstance()->getConf('CHAT.group_chat'));

            });
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }

}